package com.sakura.oj.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sakura.oj.annotation.AuthCheck;
import com.sakura.oj.common.BaseResponse;
import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.common.ResultUtils;
import com.sakura.oj.constant.UserConstant;
import com.sakura.oj.exception.BusinessException;
import com.sakura.oj.exception.ThrowUtils;
import com.sakura.oj.model.dto.judge.JudgeCaseAddRequest;
import com.sakura.oj.model.dto.problem.ProblemAddRequest;
import com.sakura.oj.model.dto.problem.ProblemQueryRequest;
import com.sakura.oj.model.dto.problem.ProblemUpdateRequest;
import com.sakura.oj.model.entity.Problem;
import com.sakura.oj.model.entity.ProblemJudgeCase;
import com.sakura.oj.model.entity.ProblemTag;
import com.sakura.oj.model.enums.DifficultyEnum;
import com.sakura.oj.model.enums.ProblemStatusEnum;
import com.sakura.oj.model.vo.LoginUserVO;
import com.sakura.oj.model.vo.ProblemVO;
import com.sakura.oj.service.ProblemJudgeCaseService;
import com.sakura.oj.service.ProblemService;
import com.sakura.oj.service.ProblemTagService;
import com.sakura.oj.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题目接口
 *
 * @author sakura
 */
@RestController
@RequestMapping("/problem")
@Slf4j
public class ProblemController {

    @Resource
    private ProblemService problemService;

    @Resource
    private ProblemTagService problemTagService;

    @Resource
    private ProblemJudgeCaseService judgeCaseService;


    // region 增删改查

    /**
     * 创建题目
     *
     * @param problemAddRequest {@link ProblemAddRequest}
     * @return {@link BaseResponse}<{@link Long}>
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addProblem(@RequestBody @Validated ProblemAddRequest problemAddRequest) {
        ThrowUtils.throwIf(problemAddRequest == null, ErrorCode.PARAMS_ERROR);

        Problem problem = new Problem();
        BeanUtils.copyProperties(problemAddRequest, problem);
        // 配置信息
        problem.setJudgeConfig(JSONUtil.toJsonStr(problemAddRequest.getJudgeConfig()));

        LoginUserVO loginUser = UserHolder.getUser();
        problem.setUserId(loginUser.getId());
        if (StringUtils.isAnyBlank(problem.getDifficulty())) {
            // 默认为简单
            problem.setDifficulty(DifficultyEnum.EASY.getValue());
        }

        // 写入数据库
        boolean result = problemService.save(problem);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        // 写入标签
        List<Long> tags = problemAddRequest.getTags();
        List<ProblemTag> tagList = tags.stream().map(tagId -> {
            ProblemTag problemTag = new ProblemTag();
            problemTag.setTagId(tagId);
            problemTag.setProblemId(problem.getId());
            return problemTag;
        }).toList();
        boolean tagSave = problemTagService.saveBatch(tagList);
        if (!tagSave) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        List<JudgeCaseAddRequest> judgeCaseList = problemAddRequest.getJudgeCaseList();
        judgeCaseService.saveBatch(judgeCaseList, problem.getId());

        // 返回新写入的数据 id
        long newProblemId = problem.getId();
        return ResultUtils.success(newProblemId);
    }

    /**
     * 删除题目
     *
     * @param id 题目id，路径参数
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteProblem(@PathVariable("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 判断是否存在
        Problem oldProblem = problemService.getById(id);
        ThrowUtils.throwIf(oldProblem == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可删除
        if (UserHolder.isNotAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = problemService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 发布题目（仅管理员可用）
     *
     * @param id 题目id
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/publish/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> publishProblem(@PathVariable("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean result = problemService.updateProblemStatus(id, ProblemStatusEnum.PUBLISHED);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 取消发布（仅管理员可用）
     *
     * @param id 题目id
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/unpublish/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> unpublishProblem(@PathVariable("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean result = problemService.updateProblemStatus(id, ProblemStatusEnum.UNPUBLISHED);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新题目（仅管理员可用）
     *
     * @param problemUpdateRequest {@link ProblemUpdateRequest}
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateProblem(@RequestBody @Validated ProblemUpdateRequest problemUpdateRequest) {
        if (problemUpdateRequest == null || problemUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Problem problem = new Problem();
        BeanUtils.copyProperties(problemUpdateRequest, problem);
        problem.setJudgeConfig(JSONUtil.toJsonStr(problemUpdateRequest.getJudgeConfig()));

        // 判断是否存在
        long id = problemUpdateRequest.getId();
        Problem oldProblem = problemService.getById(id);
        ThrowUtils.throwIf(oldProblem == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = problemService.updateById(problem);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        // 更新标签和用例
        problemService.updateProblemTagsAndCases(id, problemUpdateRequest.getTags(), problemUpdateRequest.getJudgeCaseList());

        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取题目（封装类）
     *
     * @param id 题目id
     * @return {@link BaseResponse}<{@link ProblemVO}>
     */
    @GetMapping("/get/vo/{id}")
    public BaseResponse<ProblemVO> getProblemVOById(@PathVariable long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        Problem problem = new Problem();
        problem.setId(id);

        // 获取封装类
        ProblemVO problemVO = problemService.getProblemVO(problem);

        // 查询用例信息
        int limit = 3;
        LoginUserVO loginUserVO = null;
        try {
            loginUserVO = UserHolder.getUser();
        } finally {
            LambdaQueryWrapper<ProblemJudgeCase> queryWrapper = new LambdaQueryWrapper<ProblemJudgeCase>();
            queryWrapper.eq(ProblemJudgeCase::getProblemId, id);
            if (loginUserVO != null && loginUserVO.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
                limit = 1000;
            }
            queryWrapper.last("limit " + limit);
            List<ProblemJudgeCase> judgeCases = judgeCaseService.list(queryWrapper);
            problemVO.setJudgeCaseList(judgeCases);
        }


        return ResultUtils.success(problemVO);
    }

    /**
     * 分页获取题目列表（仅管理员可用）
     *
     * @param problemQueryRequest {@link ProblemQueryRequest}
     * @return {@link BaseResponse}<{@link Page<Problem>}>
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Problem>> listProblemByPage(@RequestBody ProblemQueryRequest problemQueryRequest) {
        long current = problemQueryRequest.getCurrent();
        long size = problemQueryRequest.getPageSize();
        // 查询数据库
        Page<Problem> problemPage = problemService.page(new Page<>(current, size),
                problemService.getQueryWrapper(problemQueryRequest));
        return ResultUtils.success(problemPage);
    }

    /**
     * 分页获取题目列表（封装类）
     *
     * @param problemQueryRequest {@link ProblemQueryRequest}
     * @param request             请求
     * @return {@link BaseResponse}<{@link Page<ProblemVO>}>
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ProblemVO>> listProblemVOByPage(@RequestBody ProblemQueryRequest problemQueryRequest,
                                                             HttpServletRequest request) {
        long current = problemQueryRequest.getCurrent();
        long size = problemQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        // 创建分页对象
        Page<Problem> page = new Page<>(current, size);

        // 使用综合查询，直接在SQL中处理所有条件（包括标签条件）
        Page<Problem> problemPage = problemService.searchProblemPage(page, problemQueryRequest);

        // 获取封装类
        return ResultUtils.success(problemService.getProblemVOPage(problemPage, request));
    }

    // endregion
}
